package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.repository.ITravelCommentRepository;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class TravelCommentServiceImpl implements ITravelCommentService {
    @Autowired
    private ITravelCommentRepository repository;
    @Autowired
    private MongoTemplate template;

    public TravelComment saveOrUpdate(TravelComment travelComment) {
        //设置评论创建时间
        if(!StringUtils.hasLength(travelComment.getId())){
            travelComment.setCreateTime(new Date());
        }
        //设置关联的评论
        String refCommentId = travelComment.getRefComment().getId();
        if(StringUtils.hasLength(refCommentId)){
            TravelComment retComment = repository.findById(refCommentId).get();
            travelComment.setRefComment(retComment);
        }
        repository.save(travelComment);
        return travelComment;
    }

    public List<TravelComment> listAll() {
        return repository.findAll(Sort.by(Sort.Direction.ASC,"createTime"));
    }

    public List<TravelComment> getCreateTimeTop10() {
        Query query = new Query();
        query.with(Sort.by(Sort.Direction.ASC,"createTime")).limit(10);
        return template.find(query, TravelComment.class);
    }


//    public Page query(TravelCommentQuery qo) {
//        //查询条件
//        Query query = new Query();
//        if(qo.getTravelId() != -1){
//            //限制条件
//            Criteria criteria = Criteria.where("detailId").is(qo.getTravelId());
//            query.addCriteria(criteria);
//        }
//        //查询总条数
//        long count = template.count(query, TravelComment.class);
//        if(count == 0){
//            return Page.empty();
//        }
//        //分页查询对象
//        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.by(Sort.Direction.DESC, "createTime"));
//        query.with(pageable);
//        //查询符合条件的数据
//        List<TravelComment> list = template.find(query, TravelComment.class);
//        return new PageImpl(list,pageable,count);
//    }
}
